<template>
<el-row>
  <el-col :span="4" style="height: 90vh;overflow-y: scroll">
    <el-row>
      <el-col :span="24">
        <label class="label">&nbsp;&nbsp;选择题库或新建题库&nbsp;&nbsp;</label><br><br>
      </el-col>
      <el-col :span="17">
        <el-select v-model="paper.database" placeholder="选择题库" size="default" @change="getPapers">
          <el-option v-for="item in databaseList" :key="item" :label="item" :value="item"/>
        </el-select>
      </el-col>
      <el-col :span="6" style="text-align: right">
        <el-tooltip
            class="box-item"
            effect="dark"
            content="新建题库"
            placement="right-start"
        >
        <el-button type="default" class="btn-new-database" round @click="showAddDatabaseInput = true"><el-icon><Plus /></el-icon></el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="24" class="mg" v-if="showAddDatabaseInput">
        <label>输入题库名称</label><br>
        <el-input v-model="paper.database" placeholder="请输入题库名称" size="default" style="width: 100%" />
      </el-col>
    </el-row>
    <el-row class="mg">
      <el-col :span="24">
        <label class="label">&nbsp;&nbsp;当前题库下的试卷&nbsp;&nbsp;</label><br><br>
      </el-col>
     <el-col :span="24">
       <el-row>
         <el-col :span="24" style="max-height: 70vh;overflow-y: scroll">
           <el-empty description="还没有数据呢" v-if="papers.length === 0"/>
           <el-row class="mg row" v-if="papers.length > 0" v-for="(item,index) in papers" :key="index">
             <el-col :span="18">
               <label>{{ item.name }}</label><br>
               <span class="sp">发布日期：{{item.exam_date}}</span><br>
               <span class="sp">题量：{{ item.question_volume }}</span>
             </el-col>
             <el-col :span="6">
               <div style="text-align: right;width: 90%;">
                 <el-button type="primary" size="small" round @click="editPaper(index)">编辑</el-button>
                 <br>
                 <br>
                 <el-button type="default" class="delete-paper-btn" size="small" round>X</el-button>
               </div>

             </el-col>
           </el-row>
         </el-col>
       </el-row>
     </el-col>

    </el-row>
  </el-col>
  <el-col :span="20" class="add">
    <el-row v-if="!cardvisiable && !showEdit">
      <el-col :span="24">
        <el-empty description="选择一张试卷进行编辑 或 点击下方按钮开始新建">
          <el-button type="primary" round @click="newQuestion">新建试卷</el-button>
        </el-empty>
      </el-col>
    </el-row>

    <el-row class="mg" v-if="showEdit">
      <el-col :span="22" :offset="1">
        <EditPage :fName="fn"></EditPage>
      </el-col>
    </el-row>

    <el-row class="mg" v-if="cardvisiable">
      <el-col :span="22" :offset="1">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <el-row>
                <el-col :span="20">
                  <span>新建试卷</span>
                  <el-button type="success" style="margin-left: 3vw" v-if="showSaveToFileBtn" @click="saveQuestionToFile">保存试卷</el-button>
                </el-col>
                <el-col :span="4" style="text-align: right">
                  <el-button type="default" round @click="cardvisiable =false">退出</el-button>
                </el-col>
              </el-row>
            </div>
          </template>
          <div class="text item">
            <el-row>
              <el-col :span="5">
               <el-row>
                 <el-col :span="24">
                   <label>输入试卷基本信息</label>
                   <el-form class="mg" :model="paper">
                     <el-form-item label="试卷名称" required>
                       <el-input v-model="paper.name" placeholder="请输入"/>
                     </el-form-item>
                     <el-form-item label="考试时长" required>
                       <el-input v-model="paper.duration" type="number" min="0" placeholder="单位：分钟"/>
                     </el-form-item>
                     <el-form-item label="发布日期">
                       <el-col :span="24">
                         <el-date-picker
                             v-model="paper.exam_date"
                             type="date"
                             placeholder="选择时间"
                             style="width: 100%"
                         />
                       </el-col>
                     </el-form-item>

                   </el-form>
                 </el-col>
               </el-row>
                <el-row class="mg">
                  <el-col :span="24">
                    <label>新建试题</label>
                    <el-form class="mg" :model="question">
                      <el-form-item label="选择题型">
                        <el-select v-model="question.type_number" placeholder="请选择" @change="editQuestionTypeDesc">
                          <el-option label="单选题" value="1" />
                          <el-option label="多选题" value="2" />
                          <el-option label="简答题" value="3" />
                          <el-option label="判断题" value="4" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="编辑题型说明" v-if="question.type_number != 0">

                      </el-form-item>
                      <div class="mg" v-for="(item,index) in paper.question_type">

                        <el-input v-model="item.description" placeholder="例：一、单选题（1.5分/题）" >
                          <template #prepend v-if="item.type_number === '1'">单选题</template>
                          <template #prepend v-if="item.type_number === '2'">多选题</template>
                          <template #prepend v-if="item.type_number === '3'">简答题</template>
                          <template #prepend v-if="item.type_number === '4'">判断题</template>
                        </el-input>
                      </div>

                    </el-form>
                  </el-col>
                </el-row>

                <el-row class="mg" style="background: #f1f2f6;padding: 5px;border-radius: 20px">
                  <el-col :span="24">
                    <label>当前已建立的题目</label><br>
                    <el-row>
                      <el-col :span="6" v-for="(item,index) in paper.question_volume" style="text-align: center;margin-top: 1vh;max-height: 10vh;overflow-y: scroll">
                        <el-button type="primary" size="small" round @click="changeQUestion(index)">{{index+1}}</el-button>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="18" :offset="1" v-if="question.type_number">
                <el-row>
                  <el-col :span="24">
                    <el-row>
                      <el-col :span="24">
                        <label>编辑题目</label><br>
                        <el-input v-model="question.question" :rows="2" type="textarea" placeholder="请输入题目"/>
                      </el-col>
                    </el-row>
                    <el-row class="mg">
                      <el-col :span="24">
                        <label>选择模块</label><br>
                        <el-select v-model="question.question_module" placeholder="请选择">
                          <el-option :label="item.module" :value="item.module" v-for="(item,index) in modules" :key="index"/>
                        </el-select>
                        <el-tooltip class="box-item" effect="dark" content="新增模块" placement="top-start">
                          <el-button type="default" @click="showAddModule = true">+</el-button>
                        </el-tooltip>
                        <el-tooltip class="box-item" effect="dark" content="删除当前选中模块" placement="right-start">
                          <el-button type="default" v-if="question.question_module" @click="deleteModule">-</el-button>
                        </el-tooltip>
                        <br>
                        <el-input class="mg" v-model="newModuleName" v-if="showAddModule"  placeholder="请输入模块名称" style="width: 40%"/>
                        <el-tooltip class="box-item" effect="dark" content="确认" placement="right-start" v-if="showAddModule">
                          <el-button class="mg" type="default" v-if="showAddModule" @click="comfirmNewModule"><el-icon><Select /></el-icon></el-button>
                        </el-tooltip>
                      </el-col>
                    </el-row>
                    <el-row class="mg">
                      <el-col :span="24">
                        <label>设置分数</label><br>
                        <el-input v-model="question.score" placeholder="请输入分数" style="width: 40%" type="number" min="0"/>
                      </el-col>
                    </el-row>
                    <el-row class="mg" v-if="question.type_number === '1' || question.type_number === '2'">
                      <el-col :span="24">
                        <label>设置选项数量</label><br>
                        <el-input v-model="optionLength" placeholder="请输入选项数量：最大10" style="width: 40%" type="number" min="0" max="10" @change="initanswer" @input="initanswer"/>
                      </el-col>
                    </el-row>
                    <el-row class="mg option" v-if="question.type_number === '1' || question.type_number === '2'">
                      <el-col :span="24">
                        <el-row class="mg" v-for="item in Number(optionLength)" :key="item">
                          <el-col :span="24">
                            <el-input v-model="answer[item-1].text" placeholder="请输入">
                              <template #prepend >选项：{{alphabet[item-1]}}</template>
                            </el-input>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                    <el-row class="mg">
                      <el-col :span="24">
                        <label>设置正确答案</label><br>
                        <el-radio-group v-model="question.right[0]" class="ml-4" v-if="question.type_number === '1'">
                          <el-radio class="mg" :label="alphabet[item-1]" size="default" border v-for="item in Number(optionLength)" :key="item" />
                        </el-radio-group>

                        <el-checkbox v-if="question.type_number === '2'" v-model="question.right[item-1]" :label="alphabet[item-1]" class="mg" size="default" border v-for="item in Number(optionLength)" :key="item" />

                        <el-input v-model="question.right[0]" v-if="question.type_number === '3'" :rows="2" type="textarea" placeholder="请输入答案"/>

                        <el-radio-group v-model="question.right[0]" class="ml-4" v-if="question.type_number === '4'">
                          <el-radio class="mg" label="A" size="default" border>正确</el-radio>
                          <el-radio class="mg" label="B" size="default" border>错误</el-radio>
                        </el-radio-group>
                      </el-col>
                    </el-row>

                    <el-row class="mg">
                      <el-col :span="24">
                        <label>添加解析</label><br>
                        <el-input v-model="question.correct_answer" :rows="2" type="textarea" placeholder="请输入解析"/>
                      </el-col>
                    </el-row>

                    <el-row class="mg">
                      <el-col :span="24">
                        <el-button type="primary" @click="saveQuestion">保存题目</el-button>

                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </el-col>
</el-row>
</template>

<script setup>
import {ref, reactive, watch,onMounted} from 'vue'
import useDatabaseStore from "../../store/databaseStore";
import EditPage from "./EditPage.vue";
import useShowPageStore from "../../store/showPageStore"

const sp = useShowPageStore()
const st = useDatabaseStore()

const number = ref(0)
const cardvisiable = ref(false)
const showAddModule = ref(false)

const paper = ref({database: '', name: '', exam_date: '', duration: 0, question_volume: 0, question_type: [], questions: []})
const question= ref({type_number: '',question_number: '',question_module: "",score: '',question: '',answer: [],right: [],correct_answer: ''})
const answer = ref([])
const optionLength = ref(0)
const save_question_data = ref()
const databaseList = ref([])
const papers = ref([])
const showSaveToFileBtn = ref(false)
const showAddDatabaseInput = ref(false)
const isEdit = ref(false)
const showEdit = ref(false)
const fn = ref("")
const newModuleName = ref("")
const modules = ref([])

const alphabet = Array.from({length: 26}, (_, i) => String.fromCharCode(65 + i));

const deleteModule = () => {
    let modules = JSON.parse(localStorage.getItem("modules"))
  for (let i = 0; i < modules.length; i++) {
    if (modules[i].module === question.value.question_module){
      modules.splice(i,1)
      myApi.alert("模块删除成功","info")
    }
  }
  localStorage.removeItem("modules")
  localStorage.setItem("modules",JSON.stringify(modules))
}

const comfirmNewModule = () => {
  if (localStorage.getItem("modules")){
    let modules = JSON.parse(localStorage.getItem("modules"))
    modules.push({"module": newModuleName.value,"count": 0})
    localStorage.removeItem("modules")
    localStorage.setItem("modules",JSON.stringify(modules))
  }
  else {
    let data = {"module": newModuleName.value,"count": 0}
    localStorage.setItem("modules",JSON.stringify([data]))
  }
  modules.value = JSON.parse(localStorage.getItem('modules'))
  showAddModule.value = false
  question.value.question_module = newModuleName.value
  newModuleName.value = ""
  myApi.alert("模块添加成功","info")

}

const editPaper =  (index) => {
    showEdit.value = true
  fn.value = papers.value[index].file_name
  sp.setEditPage(true)
}

const changeQUestion = (index) => {
  question.value = paper.value.questions[index]
  optionLength.value = paper.value.questions[index].answer.length
  answer.value = paper.value.questions[index].answer
  let tempList = new Array(optionLength.value).fill(0)
  const result = tempList.map((value, index) => alphabet[index]);
  if (question.value.type_number === "2"){
    question.value.right =  result.map(value => question.value.right.includes(value) ? true : false);
  }

}

const editQuestionTypeDesc = () => {
  let type_length = paper.value.question_type.length
  if (type_length === 0){
    paper.value.question_type.push({"type_number": question.value.type_number,"description": ""})
  }
  else {
    let numList = []
    for (let i = 0; i < type_length; i++) {
      numList.push(paper.value.question_type[i].type_number)
    }
    if (!numList.includes(question.value.type_number)){
      paper.value.question_type.push({"type_number": question.value.type_number,"description": ""})
    }
  }

  paper.value.question_type.sort((a, b) => a.type_number - b.type_number);
}

const newQuestion = () => {
  if (paper.value.database !== ''){
    cardvisiable.value = true
  }
  else {
    myApi.alert("请先选择题库 或 新建题库","info")
  }
}

const initanswer = () => {
  if (!isEdit.value){
    console.log(answer.value)
    answer.value = []
    for (let i = 0; i < optionLength.value; i++) {
      answer.value.push({"option":alphabet[i],"text": ""})
    }
  }
}
const saveQuestion = () => {
  if (paper.value.name === ""){
    myApi.alert("请先填写试卷名称","info")
    return
  }
  else if (paper.value.duration <= 0){
    myApi.alert("请先设置考试时长","info")
    return
  }
  else if (question.value.question === ""){
    myApi.alert("请先设置题目","info")
    return
  }
  showSaveToFileBtn.value = true
  let filteredResult = []
  if (question.value.type_number === '2'){
    const result = question.value.right.map((value, index) => value ? alphabet[index] : value);
    filteredResult = result.filter(value => value !== false);
  }
  if (filteredResult.length > 0 ){
    question.value.right = filteredResult
  }
  paper.value.exam_date = new Date(paper.value.exam_date).toLocaleDateString()
  for (let i = 0; i < answer.value.length; i++) {
    let tmp = {"option": answer.value[i].option, "text": answer.value[i].text}
    question.value.answer.push(tmp)
  }

  paper.value.questions.push(question.value)
  paper.value.question_volume =  paper.value.questions.length
  save_question_data.value = paper
  question.value.question_number = number.value+1
  question.value = {type_number: '',question_number: '',score: '',question: '',answer: [],right: [],correct_answer: ''}
  answer.value = []
  optionLength.value = 0
  number.value++
}

const getPapers = () => {
  papers.value = []
  for (let i = 0; i < st.result.dbs.length; i++) {
    if (st.result.dbs[i].database === paper.value.database){
      papers.value.unshift(st.result.dbs[i])
    }
  }
}

const saveQuestionToFile = async () => {
 await myApi.saveJsonFile(JSON.stringify(paper.value))
  cardvisiable.value = false
  if (localStorage.getItem("modules")){
    let modules = JSON.parse(localStorage.getItem("modules"))
    for (let i = 0; i < paper.value.questions.length; i++) {
      for (let j = 0; j < modules.length; j++) {
        if (paper.value.questions[i].question_module === modules[j].module){
          modules[j].count++
        }
      }
    }
    localStorage.removeItem("modules")
    localStorage.setItem("modules", JSON.stringify(modules))
  }
  papers.value.push(paper.value)
}

const test = () => {
  alert(question.value.right)
}

onMounted(()=>{
if (st.result){
  for (let i = 0; i < st.result.dbs.length; i++) {
    databaseList.value.push(st.result.dbs[i].database)
  }
  databaseList.value = [...new Set(databaseList.value)];
}
  modules.value = JSON.parse(localStorage.getItem('modules'))
})

watch(
    [() => optionLength.value,() => sp.editPage],
    ([newValue1,newValue2]) => {
      if (newValue1 > 10){
        optionLength.value = 10
      }
      if (newValue2 === false){
        showEdit.value = false
      }
    }
);

</script>

<style scoped>
.add {
  background-color: whitesmoke;
  height: 90vh;
  overflow-y: scroll;
  border-radius: 20px
}
.label {
  background: linear-gradient(90deg, rgba(0, 228, 255, 1) 0%, rgba(129, 222, 216, 1) 100%);
  border-bottom-right-radius: 50px;
  //border-top-left-radius: 50px;
  color: white;
  font-weight: bolder;
}
.sp{
  font-size: smaller;
}
.row{
  background: linear-gradient(90deg, rgba(0,255,171,1) 0%, rgba(129,209,222,1) 100%);
  border-radius: 20px;
  padding: 10px;
}
.box-card {
  width: 100%;
  border-radius: 20px;
  height: 85vh;
  overflow-y: scroll;
}
.option{
  max-height: 30vh;
  overflow-y: scroll;
}
.btn-new-database{
  background: transparent;
}
.btn-new-database:hover{
  background: linear-gradient(90deg, rgba(0,255,235,1) 0%, rgba(129,193,222,1) 100%);
}
.delete-paper-btn{
  background: transparent;
  border: none;
}
.delete-paper-btn:hover{
  background: orange;
}
</style>